package cn.itcast.jx.util;

import java.util.Properties;

import javax.mail.Address;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import com.sun.mail.util.MailSSLSocketFactory;

public class MailUtils {
	
	/**
	 * 
	 * 
	 * @param toAddress 接收者
	 * @param subject 主题
	 * @param text 邮件内容
	 * @throws Exception 
	 */
	public static void sendMail(String addr,String subject,String text) throws Exception{
		Properties props=new Properties();
		props.put("mail.smtp.host","smtp.sina.com");
		props.put("mail.smtp.auth","true");
		Session session=Session.getInstance(props);
		//构造信息体 
		MimeMessage message =new MimeMessage(session);
		 //发件地址 
		Address address = new InternetAddress("wwwitcastcn@sina.com"); 
		message.setFrom(address);
		//收件地址 
		Address toAddress = new InternetAddress(addr); 
		message.setRecipient(MimeMessage.RecipientType.TO, toAddress);
		//主题 
		message.setSubject(subject);
		//正文 
		message.setText(text);
		message.saveChanges();
		Transport transport = session.getTransport("smtp"); 
		transport.connect("smtp.sina.com", "wwwitcastcn@sina.com", "itcast"); //发送 
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
		
	}
	
	
	public static void sendQQMail(String toAddress,String subject,String text) throws Exception {
		//1 设置邮件接收的参数
		Properties props = new Properties();
		MailSSLSocketFactory sf = new MailSSLSocketFactory();
		sf.setTrustAllHosts(true);
		props.put("mail.smtp.ssl.enable", "true");
		props.put("mail.smtp.ssl.socketFactory", sf);
		props.put("mail.smtp.host", "smtp.qq.com");
		props.put("mail.smtp.auth", "true");
		//2 获取连接
		Session session = Session.getInstance(props);
		
		//3 创建邮件
		MimeMessage mimeMessage = new MimeMessage(session);
		//4 设置发送者
		InternetAddress address = new InternetAddress("601506131@qq.com");
		mimeMessage.setFrom(address);
		
		//5 设置接收者
		InternetAddress toAddress2 = new InternetAddress(toAddress);
		mimeMessage.setRecipient(RecipientType.TO, toAddress2);
		
		//6 设置邮件内容
		mimeMessage.setSubject(subject);
		mimeMessage.setText(text);
		mimeMessage.saveChanges();
		//7 坐火箭
		Transport transport = session.getTransport("smtp");
		transport.connect("smtp.qq.com", "601506131@qq.com", "viquayststeabbdg");
		transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
		transport.close();
	}
	public static void main(String[] args) throws Exception {
		sendQQMail("601506131@qq.com", "您的快递到了","您订购的充气娃娃到了");
	}
}
